package com.example.lotterysystem.common.interceptor;

import com.example.lotterysystem.common.utils.JWTUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: Li_Xiaochi
 * Date: 2025/8/7
 * Time: 0:13
 */
@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    /**
     * 预处理，业务请求之前调用
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取请求头
        String token = request.getHeader("user_token");
        log.info("获取token: {}", token);
        log.info("获取路径: {}", request.getRequestURL());
        // 令牌解析
        Claims claims = JWTUtil.parseJWT(token);
        if (claims == null) {
            log.error("解析 JWT 令牌失败");
            response.setStatus(401);
            return false;
        }
        log.info("解析 JWT 令牌成功");
        return true;
    }
}
